import { defineStore } from "pinia";
import { worker } from "./RequestWork";
// 定义用户信息接口
interface UserInfo {
  username: string;
  id: number;
  role: string;
}
// 定义账户信息接口
interface AccountInfo {
  info?: UserInfo;
  token?: string;
}
// 持久化存储的键名
const localStorageKey = 'shop.user';
// 定义共享的状态仓库
export default defineStore('loginState', {
  // 账户状态数据
  state: (): AccountInfo => {
    // 尝试读取本地缓存数据
    let localInfo = localStorage.getItem(localStorageKey);
    let info: AccountInfo = {};   
    if (localInfo !== null) {
      // 进行JSON数据解析
      info = JSON.parse(localInfo);
    }
    if(info.token){
      worker.defaults.headers.token = info.token;
    }
    // 初始化的账户数据
    return {
      info: info.info,
      token: info.token
    };
  },
  // 计算数据
  getters: {
    // 当前是否是登录态
    isLogin: (state): boolean => {
      return (state.token !== undefined && state.token!.length > 0);
    }
  },
  // 定义行为
  actions: {
    // 登录行为
    login(info: AccountInfo) {
      this.info = info.info;
      this.token = info.token;
      // 将账户数据编码为JSON字符串后存储到本地
      localStorage.setItem(localStorageKey, JSON.stringify(info));
      if(info.token){
      worker.defaults.headers.token = info.token;
    }
    },
    // 登出行为
    logout() {
      // 清空数据
      this.info = undefined;
      this.token = undefined;
      localStorage.removeItem(localStorageKey);
      worker.defaults.headers.token=""
    }
  }
});
export type { UserInfo }